package com.atguigu.juc.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description: 公平锁和非公平锁
 * @author： yeswater
 * @create： 2024/5/29
 */

public class SaleTicketDemo {
	
	private static class Ticket {
		private int number = 50;
		
		Lock lockUnfair = new ReentrantLock(); // false : 非公平锁
		Lock lockFair = new ReentrantLock(true); // false : 公平锁
		
		public void sale() {
			lockUnfair.lock();
			try {
				if (number > 0) {
					System.out.println(Thread.currentThread().getName() + "卖出第: " + number-- + " 还剩下: " + number);
				}
			} finally {
				lockUnfair.unlock();
			}
		}
	}
	
	public static void main(String[] args) {
		Ticket ticket = new Ticket();
		
		new Thread(() -> {
			for (int i = 0; i < 55; i++) {
				ticket.sale();
			}
		}, "t1").start();
		new Thread(() -> {
			for (int i = 0; i < 55; i++) {
				ticket.sale();
			}
		}, "t2").start();
		new Thread(() -> {
			for (int i = 0; i < 55; i++) {
				ticket.sale();
			}
		}, "t3").start();
	}
	
}
